package com.example.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.DishTagsEntity;
import com.example.exception.BaseException;
import com.example.mybatis.service.impl.CrudServiceImpl;
import com.example.dao.TagsDao;
import com.example.dto.TagsDTO;
import com.example.entity.TagsEntity;
import com.example.service.TagsService;
import com.example.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 标签
 *
 * @author yyyyjinying 1020066395@qq.com
 * @since 1.0-SNAPSHOT 2025-04-29
 */
@Service
public class TagsServiceImpl extends CrudServiceImpl<TagsDao, TagsEntity, TagsDTO> implements TagsService {
    @Autowired
    private Snowflake snowflake;
    @Override
    public QueryWrapper<TagsEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<TagsEntity> wrapper = new QueryWrapper<>();


        return wrapper;
    }
    @Override
    public void delete(Long[] tagIds) {
        Long dishId = tagIds[0];
        Long tagId = tagIds[1];
        List<DishTagsEntity> records = baseDao.selectRelationByTag(tagId);
        List<DishTagsEntity> collect = records.stream().filter(item -> !item.getDishId().equals(dishId)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)){
            List<Long> collect1 = collect.stream().map(DishTagsEntity::getDishId).collect(Collectors.toList());
            throw new BaseException("该标签已绑定其他菜品，无法删除 " + JSONObject.toJSONString(collect1));
        } else {
            Long[] ids = {tagId};
            super.delete(ids);
        }
    }


    @Override
    public List<TagsDTO> tagByDishId(Long dishId) {
        List<TagsEntity> tagsEntities = baseDao.tagByDishId(dishId, null);
        List<TagsDTO> collect = tagsEntities.stream().map(item -> {
            TagsDTO tagsDTO = ConvertUtils.sourceToTarget(item, TagsDTO.class);
            tagsDTO.setChecked(true);
            tagsDTO.setType("success");
            return tagsDTO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void saveAndUpdateTag(Long dishId, List<TagsDTO> tagLists) {
        if (CollectionUtils.isEmpty(tagLists)) {
            return;
        }
        List<TagsDTO> updateData = new ArrayList<>();
        List<TagsDTO> insertData = new ArrayList<>();
        for (TagsDTO item : tagLists) {
            if (item != null) { // 增加对item的非空检查
                if (shouldUpdate(item)) { // 使用提取的方法简化逻辑并提高可读性
                    updateData.add(item);
                } else {
                    // 新增生成唯一id
                    item.setTagId(snowflake.nextId());
                    insertData.add(item);
                }
            }
        }

        if (!CollectionUtils.isEmpty(updateData)) {
            super.updateBatchById(ConvertUtils.sourceToTarget(updateData, TagsEntity.class));
        }

        if (!CollectionUtils.isEmpty(insertData)) {
            // 1 新增标签
            List<TagsEntity> tagsEntities = ConvertUtils.sourceToTarget(insertData, TagsEntity.class);
            super.insertBatch(tagsEntities);
        }

        // 根据插入的数据流，筛选出已选中的标签，映射为DishTagsEntity对象集合
        List<DishTagsEntity> dishTagsEntityCollect = tagLists.stream().filter(TagsDTO::getChecked).map(item -> {
            DishTagsEntity dishTagsEntity = new DishTagsEntity();
            dishTagsEntity.setTagId(item.getTagId());
            dishTagsEntity.setDishId(dishId);
            return dishTagsEntity;
        }).collect(Collectors.toList());

        // 删除菜单下的所有标签
        baseDao.deleteDishTagRelation(ListUtil.of(dishId), null);
        // 批量插入新的菜标签关系
        if (!CollectionUtils.isEmpty(dishTagsEntityCollect)) {
            baseDao.batchInsertDishTagRelation(dishTagsEntityCollect);
        }

    }

    private boolean shouldUpdate(TagsDTO item) {
        return item.getTagId() != null;
    }
}